package com.cubesugar2014.secretcard;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.cubesugar2014.secretcard.SService;
import com.cubesugar2014.secretcard.SContent;
import com.cubesugar2014.secretcard.SContent.SItem;
import com.cubesugar2014.secretcard.R;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Notification.BigPictureStyle;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.PopupMenu;
import android.widget.Toast;


/**
 * An activity representing a list of Items. This activity
 * has different presentations for handset and tablet-size devices. On
 * handsets, the activity presents a list of items, which when touched,
 * lead to a {@link ItemDetailActivity} representing
 * item details. On tablets, the activity presents the list of items and
 * item details side-by-side using two vertical panes.
 * <p>
 * The activity makes heavy use of fragments. The list of items is a
 * {@link ItemListFragment} and the item details
 * (if present) is a {@link ItemDetailFragment}.
 * <p>
 * This activity also implements the required
 * {@link ItemListFragment.Callbacks} interface
 * to listen for item selections.
 */
public class ItemListActivity extends FragmentActivity
        implements ItemListFragment.Callbacks {

	
	static public void FLOG(String text)
	{       
/*	   File logFile = new File("sdcard/log_sc.txt");
	   if (!logFile.exists())
	   {
	      try
	      {
	         logFile.createNewFile();
	      } 
	      catch (IOException e)
	      {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }
	   try
	   {
	      //BufferedWriter for performance, true to set append to file flag
	      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
	      buf.append(text);
	      buf.newLine();
	      buf.flush();
	      buf.close();
	   }
	   catch (IOException e)
	   {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	   }
	*/
	}
	
    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;
	
    private NotificationManager mManager; 
	private Notification.Builder mBuilder;
	private Bitmap mBitmap;
    private String mInputText;
    private AlertDialog.Builder mDBuilder;
	
    public static final String PREFS_NAME = "ScardPrefsFile";

  
    
    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
    
    private Bitmap _LoadPicture(String seedKey) 
	{
    	SContent.lock.lock();
    	
    	FLOG("LoadPicture 1");
		byte[] encryptedData = null;
        
        try {
        	FLOG("LoadPicture 2" + seedKey);
        		
			FileInputStream fIn = openFileInput(seedKey + ".bin");
			long size = fIn.getChannel().size();
			FLOG("LoadPicture 3" + size);
			
			if (size <= 0 )
			{
				SContent.lock.unlock();
	            return null;
			}
			FLOG("LoadPicture 4");
			
			encryptedData = new byte[(int) size] ;
			
			FLOG("LoadPicture 5");
			
			fIn.read(encryptedData);
			fIn.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			SContent.lock.unlock();
		    return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			SContent.lock.unlock();
		    return null;
		}
    	FLOG("LoadPicture 6");
    	
		byte[] key = seedKey.getBytes();    
		MessageDigest sha = null;
		try {
			sha = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		FLOG("LoadPicture 7" + sha);
		
		key = sha.digest(key);
		key = Arrays.copyOf(key, 16); // use only first 128 bit
		
		byte[] decryptedData = null;
		FLOG("LoadPicture 8" + key);
		
		// decrypt
		try {
			decryptedData = decrypt(key, encryptedData);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		SContent.lock.unlock();
		FLOG("LoadPicture 9 " + decryptedData);
				
		if (decryptedData == null )
			return null;
		else
			return BitmapFactory.decodeByteArray(decryptedData, 0, decryptedData.length);
			
    }

    @Override
    protected void onStart()
    {
FLOG("onStart 1 ");
    	super.onStart();
    	

FLOG("onStart 2 ");
    	// Restore preferences
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String recentKey = settings.getString("recentKey", null);
        Bitmap bitmap = null;

FLOG("onStart 3 ");
        if (recentKey != null)
        {
            bitmap = _LoadPicture(recentKey);

FLOG("onStart 3-1 ");
            if (bitmap == null)
            	return;

FLOG("onStart 3-2 ");
        	ImageView iView = (ImageView)findViewById(R.id.ImageView01);
			iView.setImageBitmap(bitmap);
			
			mBitmap = bitmap;
        }

FLOG("onStart 4 ");
    }
    
    static void ItemInit(Context context)
    {
    	 if (SContent.ITEMS.size() <= 0 )   
         {
         	int i = 1;
 	  	
         	try {
 				
 	  		  // open the file for reading
 	  		  FileInputStream instream = context.openFileInput("listitem.bin");
 				  		  
 	  		  if (instream != null) 
 	  		  {
 	  			  InputStreamReader inputreader = new InputStreamReader(instream);
 	  			  BufferedReader buffreader = new BufferedReader(inputreader);
 	
 	  			  String line;
 	
 	  			  // read every line of the file into the line-variable, on line at the time
 	  			  do {
 	  			     line = buffreader.readLine();
 	  			    
 	  			     if (line == null) break;
 	  			   
 	  			     // do something with the line 
 	  			     SContent.addItem(new SItem(String.valueOf(i), line));
 	  			     i++;
 	  			     
 	  			  } while (line != null);
 	  		  }
 	  		    			
 			} catch (FileNotFoundException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			} catch (IOException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			}
         }
    	 
    	 if (SContent.ITEMS.size() <= 0 )
		  	{
		        // Add 3 sample items.
		  		SContent.addItem(new SItem("0", "Credit Card"));
		  		SContent.addItem(new SItem("1", "Secret Card"));
		  		SContent.addItem(new SItem("2", "Extra Image"));
		        
		        
		        FileOutputStream fOut;
				try {
					
					fOut = context.openFileOutput("listitem.bin",Context.MODE_PRIVATE);
					
					
					fOut.write("Credit Card\n".getBytes());
					fOut.write("Secret Card\n".getBytes());
					fOut.write("Extra Image\n".getBytes());
					
					fOut.close();
				    
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		       
		   }
    	 
    }
    @SuppressLint("WrongViewCast")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_list);

        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-large and
            // res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            // In two-pane mode, list items should be given the
            // 'activated' state when touched.
            ((ItemListFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.item_list))
                    .setActivateOnItemClick(true);
        }

        // TODO: If exposing deep links into your app, handle intents here.
	  
        ItemInit(this);
	  	
		mDBuilder = new AlertDialog.Builder(this);
		mDBuilder.setTitle("New Card Name");
		// Set up the input
		final EditText input = new EditText(this);
		input.setInputType(InputType.TYPE_CLASS_TEXT);
   		mDBuilder.setView(input);
   	 

		// Set up the buttons
		mDBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		    	mInputText = input.getText().toString();
		    
		    	for (int i = 0; i < SContent.Count() ; i++)
	    		{
	    			if (SContent.ITEMS.get(i).content.equals(mInputText))
	    			{
	    				Toast.makeText(getApplicationContext(), "This name is already used", Toast.LENGTH_LONG).show();
	    				finish();
	            		startActivity(getIntent());
	            		
	    				return;
	    			}
	    		}
		    	
		    	if (mInputText != null  && !mInputText.isEmpty())
        		{
		    		
        			int n = SContent.Count();
        		//SContent.addItem(new SItem(String.valueOf(n), "New Card #" + String.valueOf(n)));
        			SContent.addItem(new SItem(String.valueOf(n), mInputText));
        			
        			FileOutputStream fOut;
        				try {
        					fOut = openFileOutput("listitem.bin",Context.MODE_APPEND | Context.MODE_PRIVATE);
        					        					
        					fOut.write((mInputText + "\n").getBytes());
        					
        					fOut.close();
        				    
        				} catch (IOException e) {
        					// TODO Auto-generated catch block
        					e.printStackTrace();
        				}
        				
        			
        		}
		    	
		    	
		    	finish();
        		startActivity(getIntent());
        		
		    }
		});
		
		mDBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		    	
		    	dialog.cancel();
		    	//dialog.dismiss();
		    	
		    	//finish();
				finish();
        		startActivity(getIntent());
		    }
		});
		
        Button newCard = (Button)findViewById(R.id.button02);
         
		
    	
        newCard.setOnClickListener(new OnClickListener(){
        
        	@Override
        	public void onClick(View v)
        	{
        		mDBuilder.show();
        	 //   Toast.makeText(getApplicationContext(), "New Card", Toast.LENGTH_LONG).show();
        	    
        	}
        });
        
        /*
        // Restore preferences
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String recentKey = settings.getString("recentKey", null);
        Bitmap bitmap = null;
        
        if (recentKey != null)
        {
            bitmap = _LoadPicture(recentKey);
            
            if (bitmap == null)
            	return;
            
        	ImageView iView = (ImageView)findViewById(R.id.ImageView01);
			iView.setImageBitmap(bitmap);
			
			mBitmap = bitmap;
        }
        */
        Button activate = (Button)findViewById(R.id.button01);
    	
        mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, ItemListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
				
		 
		mBuilder = new Notification.Builder(this);
		mBuilder.setSmallIcon(R.drawable.ic_launcher);
		mBuilder.setTicker("Activated your card");
		mBuilder.setWhen(System.currentTimeMillis());
		//mBuilder.setNumber(1);
		mBuilder.setContentTitle("Notification.Builder Title");
		mBuilder.setContentText("Notification.Builder Massage");
		mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
		mBuilder.setContentIntent(pendingIntent);
		mBuilder.setAutoCancel(true);
		 
		mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
		
        activate.setOnClickListener(new OnClickListener(){
        	
        	@Override
        	public void onClick(View v)
        	{
        		//ImageView iView = (ImageView)findViewById(R.id.imageView1);
        		//Bitmap bigPicture = iView.getDrawingCache(true);
        		//Bitmap bigPicture = mBitmap;
        		if (mBitmap != null)
        		{
        				
        			CheckBox cb = (CheckBox)findViewById(R.id.checkBox1);
        			
        			Bitmap bigPicture;
        			
        			if (cb.isChecked())
        				bigPicture = Bitmap.createScaledBitmap(mBitmap, mBitmap.getWidth(), mBitmap.getWidth()/2, false);
        			else 
        				bigPicture = mBitmap;
        			    		
	        		Notification.BigPictureStyle bigStyle = new BigPictureStyle(mBuilder);
	        		bigStyle.setBigContentTitle("Your secret card");
	        		bigStyle.setSummaryText("Activated your image");
	        		bigStyle.bigPicture(bigPicture);
	        		 
	        		mBuilder.setStyle(bigStyle);
	        		mManager.notify(111, mBuilder.build());
	        	}
        	   
        	           	      
            }
        });
        
        ImageButton setup = (ImageButton)findViewById(R.id.imageButtonSetup);
        setup.setOnClickListener(new OnClickListener(){
        
        	@Override
        	public void onClick(View v)
        	{
        		Intent i = new Intent(ItemListActivity.this, SetupActivity.class);
    			startActivity(i);
        	}
        });
         
        if (SService.mOnWorking == false)
        {
        	startService(new Intent("com.cubesugar2014.secretcard.service")); 
        }
        
    }

    /**
     * Callback method from {@link ItemListFragment.Callbacks}
     * indicating that the item with the given ID was selected.
     */
    @Override
    public void onItemSelected(String id) {
        if (mTwoPane) {
            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a
            // fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
            ItemDetailFragment fragment = new ItemDetailFragment();
            fragment.mItem.id = id;
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.item_detail_container, fragment)
                    .commit();

        } else {
            // In single-pane mode, simply start the detail activity
            // for the selected item ID.
            Intent detailIntent = new Intent(this, ItemDetailActivity.class);
            detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
            
            CheckBox cb = (CheckBox)findViewById(R.id.checkBox1);
            detailIntent.putExtra("Scaled", cb.isChecked());
            startActivity(detailIntent);
        }
    }
    
}
